//
//  AlbumListTableViewController.m
//  DAlbum
//
//  Created by David Qiu on 15/9/2.
//  Copyright (c) 2015年 David Qiu. All rights reserved.
//

#import "AlbumListTableViewController.h"
#import "AlbumListItem.h"
#import "AlbumsManager.h"


@interface AlbumListTableViewController () <UIAlertViewDelegate>

@property (strong, atomic) NSMutableArray* albumListItems;
@property (weak, nonatomic) IBOutlet UIBarButtonItem* buttonAdd;
@property (strong, atomic) UIAlertView* alertViewNewAlbum;

@end


@implementation AlbumListTableViewController

#pragma mark - View control

- (void) viewDidLoad {
    [super viewDidLoad];
    
    // Initialize: The List of Album List Items
    self.albumListItems = [[NSMutableArray alloc] init];
    [self refreshAlbumListItems];
    
    // Initialize: Editing status
    [self setEditing:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    NSLog(@"[ INFO ] Set editing status. (status: %d)", editing);
    
    // UI: Edit button
    UIBarButtonSystemItem systemItem = (self.editing) ? (UIBarButtonSystemItemDone) : (UIBarButtonSystemItemEdit);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:systemItem target:self action:@selector(buttonEditClicked:)];
}


#pragma mark - Internal Operations

- (void) refreshAlbumListItems {
    // Check the array
    if (self.albumListItems == nil) {
        self.albumListItems = [[NSMutableArray alloc] init];
    }
    
    // Remove all original items
    [self.albumListItems removeAllObjects];
    
    // Fetch the latest albums list
    NSArray* albums = [[AlbumsManager defaultManager] albums];
    
    // Update the album list items
    for (NSUInteger i=0; i<[albums count]; ++i) {
        [self.albumListItems addObject:[[AlbumListItem alloc] initWithAlbumName:[albums objectAtIndex:i]]];
    }
    
    // Reload table view
    [self.tableView reloadData];
}


#pragma mark - Table View

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.albumListItems count];
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Construct the cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AlbumListPrototypeCell" forIndexPath:indexPath];
    AlbumListItem* item = [self.albumListItems objectAtIndex:indexPath.row];
    cell.textLabel.text = item.albumName;
    
    // Return the cell
    return cell;
}

- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    [self setEditing:YES animated:YES];
    return UITableViewCellEditingStyleDelete;
}

- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Retrieve the album name
    AlbumListItem* item = [self.albumListItems objectAtIndex:[indexPath row]];
    NSString* albumName = item.albumName;
    
    // Select editing style
    switch (editingStyle) {
        case UITableViewCellEditingStyleDelete:
        {
            // Delete the expected album
            NSLog(@"[ INFO ] Delete existing album. (album: \"%@\")", albumName);
            AlbumManagerDeleteAlbumResult result = [[AlbumsManager defaultManager] deleteAlbumByName:albumName];
            
            // Check the delete album result
            switch (result) {
                case AlbumManagerDeleteAlbumSucceeded:
                    NSLog(@"[ INFO ] Delete album succeeded. (album: \"%@\")", albumName);
                    break;
                    
                case AlbumManagerDeleteAlbumInexistent:
                    NSLog(@"[ ERROR ] Delete album not exists. (album: \"%@\")", albumName);
                    [[[UIAlertView alloc] initWithTitle:@"Error" message:@"The album to delete does not exist." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
                    break;
                    
                case AlbumManagerDeleteAlbumFailed:
                    NSLog(@"[ ERROR ] Delete album failed. (album: \"%@\")", albumName);
                    [[[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to delete the album." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
                    break;
                    
                default:
                    NSLog(@"[ ERROR ] Unexpected delete album result. (album: \"%@\", result: \"%ld\")", albumName, result);
                    break;
            }
        }
        break;
            
        default:
        {
            NSLog(@"[ Error ] Unexpected table view cell editing style. (style: %ld)", editingStyle);
            return;
        }
    }
    
    // Refresh album list items
    [self refreshAlbumListItems];
}

- (BOOL) tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

/*
// Override to support rearranging the table view.
- (void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL) tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Set selected album list item
    [AlbumsManager defaultManager].selectedAlbumName = ((AlbumListItem *)[self.albumListItems objectAtIndex:[indexPath row]]).albumName;
    NSLog(@"[ INFO ] Select album. (album: \"%@\")", [AlbumsManager defaultManager].selectedAlbumName);
    
    // Perform segue album details
    [self performSegueWithIdentifier:@"segueShowAlbumDetails" sender:self];
}


#pragma mark - Alert view delegates

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    // AlertView: New Album
    if (alertView == self.alertViewNewAlbum) {
        // Select button index
        switch (buttonIndex) {
            case 0: // Button: Cancel
            {
                NSLog(@"[ INFO ] Cancel creating new album. (index: %ld)", buttonIndex);
            }
            break;
                
            case 1: // Button: Create
            {
                // Fetch the expected new album name
                NSString* newAlbumName = [self.alertViewNewAlbum textFieldAtIndex:0].text;
                
                // Create album
                NSLog(@"[ INFO ] Create new album. (album: \"%@\")", newAlbumName);
                AlbumManagerCreateAlbumResult createAlbumResult = [[AlbumsManager defaultManager] createAlbumByName:newAlbumName];
                
                // Check the create album result
                switch (createAlbumResult) {
                    case AlbumManagerCreateAlbumSucceeded:
                        NSLog(@"[ INFO ] Create new album succeeded. (album: \"%@\")", newAlbumName);
                        break;
                        
                    case AlbumManagerCreateAlbumExisting:
                        NSLog(@"[ WARNING ] Album already exists. (album: \"%@\")", newAlbumName);
                        [[[UIAlertView alloc] initWithTitle:@"Error" message:@"Album already exists." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
                        break;
                        
                    case AlbumManagerCreateAlbumFailed:
                        NSLog(@"[ ERROR ] Create new album failed. (album: \"%@\")", newAlbumName);
                        [[[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to create new album." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
                        break;
                        
                    default:
                        NSLog(@"[ ERROR ] Unexpected create album result. (album: \"%@\", result: %ld)", newAlbumName, createAlbumResult);
                        break;
                }
                
                // Refresh album list items
                [self refreshAlbumListItems];
            }
            break;
                
            default:
            {
                NSLog(@"[ ERROR ] Unexpected button index. (index: %ld)", buttonIndex);
            }
            break;
        }
        
        return;
    }
}


#pragma mark - Button Events

- (IBAction) buttonAddClicked:(id)sender {
    // Construct the new album alert view
    self.alertViewNewAlbum = [[UIAlertView alloc] initWithTitle:@"New Album" message:@"Enter a name for this album." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Create",nil];
    self.alertViewNewAlbum.alertViewStyle = UIAlertViewStylePlainTextInput;
    self.alertViewNewAlbum.delegate = self;
    
    // Show the create album alert view
    [self.alertViewNewAlbum show];
}

- (IBAction) buttonEditClicked:(id)sender {
    // Toggle editing status
    [self setEditing:(!self.editing) animated:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
